#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
生产计划管理系统 - Production Planning Management System

功能包括：
- 生产计划制定与优化
- 产能分析与资源配置
- 生产进度跟踪监控
- 生产效率分析报告
"""

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
import json
import logging
from dataclasses import dataclass, asdict
from enum import Enum
import uuid
from collections import defaultdict
import math

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ProductionStatus(Enum):
    """生产状态枚举"""
    PLANNED = "planned"          # 已计划
    SCHEDULED = "scheduled"      # 已排程
    IN_PROGRESS = "in_progress"  # 生产中
    COMPLETED = "completed"      # 已完成
    PAUSED = "paused"           # 暂停
    CANCELLED = "cancelled"     # 已取消
    DELAYED = "delayed"         # 延期

class ProductionPriority(Enum):
    """生产优先级枚举"""
    LOW = "low"        # 低
    MEDIUM = "medium"  # 中
    HIGH = "high"      # 高
    URGENT = "urgent"  # 紧急

class ResourceType(Enum):
    """资源类型枚举"""
    MACHINE = "machine"      # 机器设备
    WORKER = "worker"        # 工人
    MATERIAL = "material"    # 原材料
    TOOL = "tool"           # 工具
    FACILITY = "facility"   # 设施

class ShiftType(Enum):
    """班次类型枚举"""
    DAY_SHIFT = "day_shift"      # 白班
    NIGHT_SHIFT = "night_shift"  # 夜班
    OVERTIME = "overtime"        # 加班

@dataclass
class Product:
    """产品信息"""
    product_id: str
    name: str
    category: str
    unit: str
    standard_cost: float
    production_time_per_unit: float  # 单位生产时间（小时）
    required_materials: Dict[str, float]  # 所需原材料及数量
    required_skills: List[str]  # 所需技能
    quality_standards: Dict[str, str]  # 质量标准
    is_active: bool = True

@dataclass
class ProductionResource:
    """生产资源"""
    resource_id: str
    name: str
    type: str
    capacity: float  # 产能（单位/小时）
    availability_hours: float  # 可用时间（小时/天）
    cost_per_hour: float
    skills: List[str]  # 技能（对于工人）
    maintenance_schedule: List[Dict]  # 维护计划
    current_utilization: float = 0.0  # 当前利用率
    is_available: bool = True

@dataclass
class ProductionOrder:
    """生产订单"""
    order_id: str
    product_id: str
    quantity: int
    priority: str
    due_date: datetime
    customer_id: str = ""
    status: str = ProductionStatus.PLANNED.value
    planned_start_date: Optional[datetime] = None
    planned_end_date: Optional[datetime] = None
    actual_start_date: Optional[datetime] = None
    actual_end_date: Optional[datetime] = None
    assigned_resources: List[str] = None
    progress_percentage: float = 0.0
    quality_score: float = 0.0
    notes: str = ""
    created_date: datetime = None
    
    def __post_init__(self):
        if self.created_date is None:
            self.created_date = datetime.now()
        if self.assigned_resources is None:
            self.assigned_resources = []

@dataclass
class ProductionSchedule:
    """生产排程"""
    schedule_id: str
    order_id: str
    resource_id: str
    start_time: datetime
    end_time: datetime
    shift_type: str
    estimated_output: float
    actual_output: float = 0.0
    efficiency: float = 0.0
    notes: str = ""

@dataclass
class ProductionReport:
    """生产报告"""
    report_id: str
    order_id: str
    report_date: datetime
    shift_type: str
    produced_quantity: int
    defect_quantity: int
    downtime_minutes: int
    efficiency_rate: float
    quality_rate: float
    operator_id: str
    notes: str = ""

class ProductionPlanningManager:
    """生产计划管理系统核心类"""
    
    def __init__(self):
        self.products: Dict[str, Product] = {}
        self.resources: Dict[str, ProductionResource] = {}
        self.orders: Dict[str, ProductionOrder] = {}
        self.schedules: Dict[str, ProductionSchedule] = {}
        self.reports: Dict[str, ProductionReport] = {}
        self.capacity_calendar: Dict[str, Dict] = {}  # 产能日历
        
    def register_product(self, product: Product) -> bool:
        """注册产品"""
        try:
            self.products[product.product_id] = product
            logger.info(f"产品 {product.name} 注册成功")
            return True
        except Exception as e:
            logger.error(f"产品注册失败: {e}")
            return False
    
    def register_resource(self, resource: ProductionResource) -> bool:
        """注册生产资源"""
        try:
            self.resources[resource.resource_id] = resource
            logger.info(f"资源 {resource.name} 注册成功")
            return True
        except Exception as e:
            logger.error(f"资源注册失败: {e}")
            return False
    
    def create_production_order(self, order_data: Dict) -> Optional[str]:
        """创建生产订单"""
        try:
            order_id = f"PO{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:6]}"
            
            order = ProductionOrder(
                order_id=order_id,
                product_id=order_data['product_id'],
                quantity=order_data['quantity'],
                priority=order_data.get('priority', ProductionPriority.MEDIUM.value),
                due_date=order_data['due_date'],
                customer_id=order_data.get('customer_id', '')
            )
            
            self.orders[order_id] = order
            
            # 自动进行初步排程
            self._auto_schedule_order(order_id)
            
            logger.info(f"生产订单 {order_id} 创建成功")
            return order_id
            
        except Exception as e:
            logger.error(f"创建生产订单失败: {e}")
            return None
    
    def _auto_schedule_order(self, order_id: str) -> bool:
        """自动排程生产订单"""
        if order_id not in self.orders:
            return False
        
        order = self.orders[order_id]
        product = self.products.get(order.product_id)
        
        if not product:
            logger.error(f"产品 {order.product_id} 不存在")
            return False
        
        # 计算所需生产时间
        total_production_time = order.quantity * product.production_time_per_unit
        
        # 寻找合适的资源
        suitable_resources = self._find_suitable_resources(product, total_production_time)
        
        if not suitable_resources:
            logger.warning(f"订单 {order_id} 暂时无法排程，缺少合适资源")
            return False
        
        # 选择最优资源组合
        selected_resources = self._optimize_resource_allocation(suitable_resources, total_production_time)
        
        # 计算排程时间
        earliest_start_time = self._calculate_earliest_start_time(selected_resources)
        planned_end_time = earliest_start_time + timedelta(hours=total_production_time)
        
        # 更新订单信息
        order.planned_start_date = earliest_start_time
        order.planned_end_date = planned_end_time
        order.assigned_resources = [r['resource_id'] for r in selected_resources]
        order.status = ProductionStatus.SCHEDULED.value
        
        # 创建详细排程
        self._create_detailed_schedule(order_id, selected_resources, earliest_start_time, total_production_time)
        
        logger.info(f"订单 {order_id} 自动排程完成")
        return True
    
    def _find_suitable_resources(self, product: Product, required_time: float) -> List[Dict]:
        """寻找合适的资源"""
        suitable_resources = []
        
        for resource in self.resources.values():
            if not resource.is_available:
                continue
            
            # 检查技能匹配（对于工人）
            if resource.type == ResourceType.WORKER.value:
                if not any(skill in resource.skills for skill in product.required_skills):
                    continue
            
            # 检查产能
            if resource.capacity > 0:
                available_capacity = self._get_available_capacity(resource.resource_id)
                if available_capacity >= required_time:
                    suitable_resources.append({
                        'resource_id': resource.resource_id,
                        'resource': resource,
                        'available_capacity': available_capacity,
                        'efficiency_score': self._calculate_resource_efficiency(resource, product)
                    })
        
        return suitable_resources
    
    def _get_available_capacity(self, resource_id: str, start_date: datetime = None) -> float:
        """获取资源可用产能"""
        if start_date is None:
            start_date = datetime.now()
        
        resource = self.resources.get(resource_id)
        if not resource:
            return 0.0
        
        # 计算未来7天的可用产能
        total_available = 0.0
        for i in range(7):
            date = start_date + timedelta(days=i)
            date_str = date.strftime('%Y-%m-%d')
            
            # 检查是否有维护计划
            maintenance_hours = 0
            for maintenance in resource.maintenance_schedule:
                if maintenance.get('date') == date_str:
                    maintenance_hours += maintenance.get('hours', 0)
            
            # 检查已排程的时间
            scheduled_hours = 0
            for schedule in self.schedules.values():
                if (schedule.resource_id == resource_id and 
                    schedule.start_time.date() == date.date()):
                    duration = (schedule.end_time - schedule.start_time).total_seconds() / 3600
                    scheduled_hours += duration
            
            daily_available = max(0, resource.availability_hours - maintenance_hours - scheduled_hours)
            total_available += daily_available
        
        return total_available
    
    def _calculate_resource_efficiency(self, resource: ProductionResource, product: Product) -> float:
        """计算资源效率评分"""
        score = 0.0
        
        # 基础产能评分
        score += resource.capacity * 0.4
        
        # 技能匹配评分
        if resource.type == ResourceType.WORKER.value:
            matching_skills = len(set(resource.skills) & set(product.required_skills))
            skill_score = matching_skills / len(product.required_skills) if product.required_skills else 0
            score += skill_score * 0.3
        
        # 成本效率评分（成本越低评分越高）
        if resource.cost_per_hour > 0:
            cost_efficiency = 1 / resource.cost_per_hour * 100
            score += cost_efficiency * 0.2
        
        # 利用率评分（利用率适中最好）
        optimal_utilization = 0.8
        utilization_score = 1 - abs(resource.current_utilization - optimal_utilization)
        score += utilization_score * 0.1
        
        return score
    
    def _optimize_resource_allocation(self, suitable_resources: List[Dict], required_time: float) -> List[Dict]:
        """优化资源分配"""
        # 按效率评分排序
        suitable_resources.sort(key=lambda x: x['efficiency_score'], reverse=True)
        
        selected_resources = []
        remaining_time = required_time
        
        for resource_info in suitable_resources:
            if remaining_time <= 0:
                break
            
            available_time = min(resource_info['available_capacity'], remaining_time)
            if available_time > 0:
                selected_resources.append({
                    'resource_id': resource_info['resource_id'],
                    'resource': resource_info['resource'],
                    'allocated_time': available_time
                })
                remaining_time -= available_time
        
        return selected_resources
    
    def _calculate_earliest_start_time(self, selected_resources: List[Dict]) -> datetime:
        """计算最早开始时间"""
        earliest_time = datetime.now()
        
        for resource_info in selected_resources:
            resource_id = resource_info['resource_id']
            
            # 找到该资源的最后一个排程结束时间
            last_end_time = datetime.now()
            for schedule in self.schedules.values():
                if (schedule.resource_id == resource_id and 
                    schedule.end_time > last_end_time):
                    last_end_time = schedule.end_time
            
            earliest_time = max(earliest_time, last_end_time)
        
        return earliest_time
    
    def _create_detailed_schedule(self, order_id: str, selected_resources: List[Dict], 
                                start_time: datetime, total_time: float):
        """创建详细排程"""
        current_time = start_time
        
        for resource_info in selected_resources:
            resource_id = resource_info['resource_id']
            allocated_time = resource_info['allocated_time']
            resource = resource_info['resource']
            
            # 计算预期产出
            estimated_output = allocated_time * resource.capacity
            
            schedule_id = f"SCH{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:6]}"
            
            schedule = ProductionSchedule(
                schedule_id=schedule_id,
                order_id=order_id,
                resource_id=resource_id,
                start_time=current_time,
                end_time=current_time + timedelta(hours=allocated_time),
                shift_type=self._determine_shift_type(current_time),
                estimated_output=estimated_output
            )
            
            self.schedules[schedule_id] = schedule
            
            # 更新资源利用率
            daily_hours = resource.availability_hours
            if daily_hours > 0:
                utilization_increase = allocated_time / (daily_hours * 7)  # 按周计算
                resource.current_utilization = min(1.0, resource.current_utilization + utilization_increase)
            
            current_time += timedelta(hours=allocated_time)
    
    def _determine_shift_type(self, time: datetime) -> str:
        """确定班次类型"""
        hour = time.hour
        if 6 <= hour < 14:
            return ShiftType.DAY_SHIFT.value
        elif 14 <= hour < 22:
            return ShiftType.DAY_SHIFT.value
        else:
            return ShiftType.NIGHT_SHIFT.value
    
    def update_production_progress(self, order_id: str, progress_data: Dict) -> bool:
        """更新生产进度"""
        if order_id not in self.orders:
            return False
        
        try:
            order = self.orders[order_id]
            
            # 更新进度
            if 'progress_percentage' in progress_data:
                order.progress_percentage = progress_data['progress_percentage']
            
            if 'status' in progress_data:
                old_status = order.status
                order.status = progress_data['status']
                
                # 更新时间戳
                if progress_data['status'] == ProductionStatus.IN_PROGRESS.value and not order.actual_start_date:
                    order.actual_start_date = datetime.now()
                elif progress_data['status'] == ProductionStatus.COMPLETED.value:
                    order.actual_end_date = datetime.now()
            
            if 'quality_score' in progress_data:
                order.quality_score = progress_data['quality_score']
            
            if 'notes' in progress_data:
                order.notes = progress_data['notes']
            
            logger.info(f"订单 {order_id} 进度更新成功")
            return True
            
        except Exception as e:
            logger.error(f"更新生产进度失败: {e}")
            return False
    
    def create_production_report(self, report_data: Dict) -> Optional[str]:
        """创建生产报告"""
        try:
            report_id = f"RPT{datetime.now().strftime('%Y%m%d%H%M%S')}{str(uuid.uuid4())[:6]}"
            
            report = ProductionReport(
                report_id=report_id,
                order_id=report_data['order_id'],
                report_date=report_data.get('report_date', datetime.now()),
                shift_type=report_data['shift_type'],
                produced_quantity=report_data['produced_quantity'],
                defect_quantity=report_data.get('defect_quantity', 0),
                downtime_minutes=report_data.get('downtime_minutes', 0),
                efficiency_rate=report_data.get('efficiency_rate', 0.0),
                quality_rate=report_data.get('quality_rate', 0.0),
                operator_id=report_data['operator_id'],
                notes=report_data.get('notes', '')
            )
            
            self.reports[report_id] = report
            
            # 更新相关排程的实际产出
            self._update_schedule_actual_output(report_data['order_id'], report_data['produced_quantity'])
            
            logger.info(f"生产报告 {report_id} 创建成功")
            return report_id
            
        except Exception as e:
            logger.error(f"创建生产报告失败: {e}")
            return None
    
    def _update_schedule_actual_output(self, order_id: str, produced_quantity: int):
        """更新排程实际产出"""
        order_schedules = [s for s in self.schedules.values() if s.order_id == order_id]
        
        if order_schedules:
            # 按时间顺序分配产出
            order_schedules.sort(key=lambda x: x.start_time)
            remaining_quantity = produced_quantity
            
            for schedule in order_schedules:
                if remaining_quantity <= 0:
                    break
                
                allocated_quantity = min(remaining_quantity, schedule.estimated_output)
                schedule.actual_output += allocated_quantity
                
                # 计算效率
                if schedule.estimated_output > 0:
                    schedule.efficiency = schedule.actual_output / schedule.estimated_output
                
                remaining_quantity -= allocated_quantity
    
    def get_capacity_analysis(self, start_date: datetime = None, 
                            end_date: datetime = None) -> Dict:
        """获取产能分析"""
        if start_date is None:
            start_date = datetime.now()
        if end_date is None:
            end_date = start_date + timedelta(days=30)
        
        analysis = {
            'period': {
                'start_date': start_date.isoformat(),
                'end_date': end_date.isoformat()
            },
            'resource_utilization': {},
            'capacity_summary': {
                'total_capacity': 0.0,
                'used_capacity': 0.0,
                'available_capacity': 0.0,
                'utilization_rate': 0.0
            },
            'bottlenecks': [],
            'recommendations': []
        }
        
        total_capacity = 0.0
        used_capacity = 0.0
        
        for resource_id, resource in self.resources.items():
            if not resource.is_available:
                continue
            
            # 计算时间段内的总产能
            days = (end_date - start_date).days
            resource_total_capacity = resource.capacity * resource.availability_hours * days
            
            # 计算已使用产能
            resource_used_capacity = 0.0
            for schedule in self.schedules.values():
                if (schedule.resource_id == resource_id and 
                    start_date <= schedule.start_time <= end_date):
                    duration = (schedule.end_time - schedule.start_time).total_seconds() / 3600
                    resource_used_capacity += duration * resource.capacity
            
            resource_available_capacity = resource_total_capacity - resource_used_capacity
            resource_utilization_rate = (resource_used_capacity / resource_total_capacity * 100) if resource_total_capacity > 0 else 0
            
            analysis['resource_utilization'][resource_id] = {
                'name': resource.name,
                'type': resource.type,
                'total_capacity': resource_total_capacity,
                'used_capacity': resource_used_capacity,
                'available_capacity': resource_available_capacity,
                'utilization_rate': round(resource_utilization_rate, 2)
            }
            
            total_capacity += resource_total_capacity
            used_capacity += resource_used_capacity
            
            # 识别瓶颈资源
            if resource_utilization_rate > 90:
                analysis['bottlenecks'].append({
                    'resource_id': resource_id,
                    'name': resource.name,
                    'utilization_rate': round(resource_utilization_rate, 2),
                    'type': 'over_utilized'
                })
            elif resource_utilization_rate < 30:
                analysis['bottlenecks'].append({
                    'resource_id': resource_id,
                    'name': resource.name,
                    'utilization_rate': round(resource_utilization_rate, 2),
                    'type': 'under_utilized'
                })
        
        # 汇总统计
        analysis['capacity_summary'] = {
            'total_capacity': round(total_capacity, 2),
            'used_capacity': round(used_capacity, 2),
            'available_capacity': round(total_capacity - used_capacity, 2),
            'utilization_rate': round((used_capacity / total_capacity * 100) if total_capacity > 0 else 0, 2)
        }
        
        # 生成建议
        overall_utilization = analysis['capacity_summary']['utilization_rate']
        if overall_utilization > 85:
            analysis['recommendations'].append("整体产能利用率较高，建议考虑增加资源或优化排程")
        elif overall_utilization < 50:
            analysis['recommendations'].append("整体产能利用率较低，建议优化资源配置或增加订单")
        
        if len(analysis['bottlenecks']) > 0:
            analysis['recommendations'].append(f"发现 {len(analysis['bottlenecks'])} 个资源瓶颈，需要重点关注")
        
        return analysis
    
    def get_production_efficiency_report(self, start_date: datetime = None, 
                                       end_date: datetime = None) -> Dict:
        """获取生产效率分析报告"""
        if start_date is None:
            start_date = datetime.now() - timedelta(days=30)
        if end_date is None:
            end_date = datetime.now()
        
        # 筛选时间范围内的订单和报告
        period_orders = [order for order in self.orders.values() 
                        if start_date <= order.created_date <= end_date]
        period_reports = [report for report in self.reports.values() 
                         if start_date <= report.report_date <= end_date]
        
        if not period_orders:
            return {'message': '指定时间范围内无生产数据'}
        
        # 基本统计
        total_orders = len(period_orders)
        completed_orders = [o for o in period_orders if o.status == ProductionStatus.COMPLETED.value]
        in_progress_orders = [o for o in period_orders if o.status == ProductionStatus.IN_PROGRESS.value]
        delayed_orders = [o for o in period_orders if o.status == ProductionStatus.DELAYED.value]
        
        # 完成率
        completion_rate = (len(completed_orders) / total_orders * 100) if total_orders > 0 else 0
        
        # 准时交付率
        on_time_orders = [o for o in completed_orders 
                         if o.actual_end_date and o.due_date and o.actual_end_date <= o.due_date]
        on_time_rate = (len(on_time_orders) / len(completed_orders) * 100) if completed_orders else 0
        
        # 平均生产周期
        avg_cycle_time = 0
        if completed_orders:
            total_cycle_time = sum(
                (o.actual_end_date - o.actual_start_date).total_seconds() / 3600 
                for o in completed_orders 
                if o.actual_start_date and o.actual_end_date
            )
            avg_cycle_time = total_cycle_time / len(completed_orders) if completed_orders else 0
        
        # 产品类别分析
        product_analysis = {}
        for order in period_orders:
            product_id = order.product_id
            if product_id not in product_analysis:
                product_analysis[product_id] = {
                    'product_name': self.products.get(product_id, {}).name if product_id in self.products else 'Unknown',
                    'total_orders': 0,
                    'completed_orders': 0,
                    'total_quantity': 0,
                    'average_quality_score': 0
                }
            
            product_analysis[product_id]['total_orders'] += 1
            product_analysis[product_id]['total_quantity'] += order.quantity
            
            if order.status == ProductionStatus.COMPLETED.value:
                product_analysis[product_id]['completed_orders'] += 1
            
            if order.quality_score > 0:
                current_avg = product_analysis[product_id]['average_quality_score']
                current_count = product_analysis[product_id]['total_orders']
                product_analysis[product_id]['average_quality_score'] = (
                    (current_avg * (current_count - 1) + order.quality_score) / current_count
                )
        
        # 资源效率分析
        resource_efficiency = {}
        for resource_id, resource in self.resources.items():
            resource_schedules = [s for s in self.schedules.values() 
                                if s.resource_id == resource_id and 
                                start_date <= s.start_time <= end_date]
            
            if resource_schedules:
                total_estimated = sum(s.estimated_output for s in resource_schedules)
                total_actual = sum(s.actual_output for s in resource_schedules)
                efficiency = (total_actual / total_estimated * 100) if total_estimated > 0 else 0
                
                resource_efficiency[resource_id] = {
                    'name': resource.name,
                    'type': resource.type,
                    'total_schedules': len(resource_schedules),
                    'estimated_output': total_estimated,
                    'actual_output': total_actual,
                    'efficiency_rate': round(efficiency, 2)
                }
        
        # 质量分析
        quality_analysis = {
            'total_reports': len(period_reports),
            'average_quality_rate': 0,
            'average_efficiency_rate': 0,
            'total_defects': 0,
            'total_downtime_hours': 0
        }
        
        if period_reports:
            quality_analysis.update({
                'average_quality_rate': round(
                    sum(r.quality_rate for r in period_reports) / len(period_reports), 2
                ),
                'average_efficiency_rate': round(
                    sum(r.efficiency_rate for r in period_reports) / len(period_reports), 2
                ),
                'total_defects': sum(r.defect_quantity for r in period_reports),
                'total_downtime_hours': round(
                    sum(r.downtime_minutes for r in period_reports) / 60, 2
                )
            })
        
        return {
            'period': {
                'start_date': start_date.isoformat(),
                'end_date': end_date.isoformat()
            },
            'summary': {
                'total_orders': total_orders,
                'completed_orders': len(completed_orders),
                'in_progress_orders': len(in_progress_orders),
                'delayed_orders': len(delayed_orders),
                'completion_rate': round(completion_rate, 2),
                'on_time_delivery_rate': round(on_time_rate, 2),
                'average_cycle_time_hours': round(avg_cycle_time, 2)
            },
            'product_analysis': product_analysis,
            'resource_efficiency': resource_efficiency,
            'quality_analysis': quality_analysis
        }
    
    def export_production_data(self, file_path: str, data_type: str = "orders") -> bool:
        """导出生产数据"""
        try:
            if data_type == "orders":
                data = []
                for order in self.orders.values():
                    order_data = asdict(order)
                    # 转换datetime对象为字符串
                    for key, value in order_data.items():
                        if isinstance(value, datetime):
                            order_data[key] = value.isoformat()
                    data.append(order_data)
            
            elif data_type == "schedules":
                data = []
                for schedule in self.schedules.values():
                    schedule_data = asdict(schedule)
                    for key, value in schedule_data.items():
                        if isinstance(value, datetime):
                            schedule_data[key] = value.isoformat()
                    data.append(schedule_data)
            
            elif data_type == "reports":
                data = []
                for report in self.reports.values():
                    report_data = asdict(report)
                    for key, value in report_data.items():
                        if isinstance(value, datetime):
                            report_data[key] = value.isoformat()
                    data.append(report_data)
            
            else:
                logger.error(f"不支持的数据类型: {data_type}")
                return False
            
            df = pd.DataFrame(data)
            df.to_csv(file_path, index=False, encoding='utf-8-sig')
            logger.info(f"{data_type} 数据已导出到 {file_path}")
            return True
            
        except Exception as e:
            logger.error(f"导出数据失败: {e}")
            return False

# 示例使用
if __name__ == "__main__":
    # 创建生产计划管理系统实例
    ppm = ProductionPlanningManager()
    
    # 注册产品
    product = Product(
        product_id="PROD001",
        name="智能手机",
        category="电子产品",
        unit="台",
        standard_cost=1500.0,
        production_time_per_unit=2.0,
        required_materials={"屏幕": 1, "电池": 1, "主板": 1},
        required_skills=["组装", "测试"],
        quality_standards={"外观": "无划痕", "功能": "全部正常"}
    )
    ppm.register_product(product)
    
    # 注册生产资源
    machine = ProductionResource(
        resource_id="MACH001",
        name="组装生产线1",
        type=ResourceType.MACHINE.value,
        capacity=10.0,
        availability_hours=16.0,
        cost_per_hour=200.0,
        skills=[],
        maintenance_schedule=[]
    )
    ppm.register_resource(machine)
    
    worker = ProductionResource(
        resource_id="WORK001",
        name="技术工人张三",
        type=ResourceType.WORKER.value,
        capacity=5.0,
        availability_hours=8.0,
        cost_per_hour=50.0,
        skills=["组装", "测试", "质检"],
        maintenance_schedule=[]
    )
    ppm.register_resource(worker)
    
    # 创建生产订单
    order_data = {
        'product_id': 'PROD001',
        'quantity': 100,
        'priority': ProductionPriority.HIGH.value,
        'due_date': datetime.now() + timedelta(days=7),
        'customer_id': 'CUST001'
    }
    
    order_id = ppm.create_production_order(order_data)
    if order_id:
        print(f"生产订单创建成功: {order_id}")
        
        # 更新生产进度
        progress_data = {
            'progress_percentage': 50.0,
            'status': ProductionStatus.IN_PROGRESS.value,
            'quality_score': 95.0,
            'notes': '生产进展顺利'
        }
        ppm.update_production_progress(order_id, progress_data)
        
        # 创建生产报告
        report_data = {
            'order_id': order_id,
            'shift_type': ShiftType.DAY_SHIFT.value,
            'produced_quantity': 50,
            'defect_quantity': 2,
            'downtime_minutes': 30,
            'efficiency_rate': 95.0,
            'quality_rate': 96.0,
            'operator_id': 'WORK001',
            'notes': '正常生产，质量良好'
        }
        
        report_id = ppm.create_production_report(report_data)
        print(f"生产报告创建成功: {report_id}")
        
        # 获取产能分析
        capacity_analysis = ppm.get_capacity_analysis()
        print("产能分析:", json.dumps(capacity_analysis, indent=2, default=str, ensure_ascii=False))
        
        # 获取生产效率报告
        efficiency_report = ppm.get_production_efficiency_report()
        print("生产效率报告:", json.dumps(efficiency_report, indent=2, default=str, ensure_ascii=False))